#version 110

uniform float stepSize;
uniform sampler2D preintegratedTF;
uniform sampler3D volume;

void main()
{
	//ortho
	vec3 rayDirection = vec3(0, 0, -1);

	vec4 currentPosition = gl_ModelViewMatrix * gl_TexCoord[0];
	vec4 result = vec4(0, 0, 0, 0);

	vec4 sf = currentPosition;
	//vec4 sb;
	for(float curPos = 0.0; curPos <= 1.0; curPos += stepSize)
	{
		vec4 rayDir4 = vec4(rayDirection.xyz, 0);
		vec4 lookupPosition4 = currentPosition + rayDir4 * curPos;

		lookupPosition4 = gl_ModelViewMatrixInverse * lookupPosition4;

		if(lookupPosition4.x > 1.0) lookupPosition4.x = 1.0;
		if(lookupPosition4.y > 1.0) lookupPosition4.y = 1.0;
		if(lookupPosition4.z > 1.0) lookupPosition4.z = 1.0;

		vec4 volV = texture3D(volume, lookupPosition4.xyz);
		vec4 volVsf = texture3D(volume, sf.xyz);
		//vec4 c = texture1D(transferFunc, volV.a);
		vec2 lookup2 = vec2(volV.a, volVsf.a);//or just 1.0 - volVsf.a?

		//this works
		vec4 c = texture2D(preintegratedTF, lookup2.xy);
		//c *= 256.0;
		//float l = abs(volV.a - volVsf.a) * 256.0;
		//if(l < 0.01) l = 1.0;
		//c /= l;
		//c.rgb *= c.a;//comment this when not using Bitmap!
		result.rgb += (1.0 - result.a)*c.rgb;
		result.a += c.a;

		//this doesn't - but should!
/*		vec4 c = texture2D(preintegratedTF, lookup2.xy);
		vec4 scaledTex = c * 65536.0;
		float l = abs(volV.a - volVsf.a) * 256.0;
		if(l == 0.0) l = 256.0;
		c.rgb /= l;
		c /= 256.0;
		//c.rgb *= c.a;
		result.rgb += (1.0 - result.a)*c.rgb;
		result.a += c.a;
*/
		//basically the same as above
/*		vec4 c = texture2D(preintegratedTF, lookup2.xy);
		float l = abs(volV.a - volVsf.a);
		if(l == 0.0) l = 1.0;
		c.rgb /= l;
		//c.rgb *= c.a;
		result.rgb += (1.0 - result.a)*c.rgb;
		result.a += c.a;
*/
		sf = lookupPosition4;

		if(result.a > 0.98)
			break;
	}
	
	gl_FragColor = result;
}